package top.hjcwzx.wrench.limiter.aop;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public abstract class AbstractCommonLimiter {
    @Autowired
    protected ApplicationContext applicationContext;

    protected Object commonFallBack(ProceedingJoinPoint pjp,
                                    Class<?> fallbackBean,
                                    String fallbackMethod
    ) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        Object[] args = pjp.getArgs();

        Object fallbackTarget = null;
        // 获取 fallback Bean 实例
        if (fallbackBean != void.class) {
            fallbackTarget = applicationContext.getBean(fallbackBean);
        } else {
            fallbackTarget = pjp.getTarget();
        }

        Method actFallbackMethod = fallbackTarget.getClass()
                .getDeclaredMethod(fallbackMethod, method.getParameterTypes());
        actFallbackMethod.setAccessible(true);
        return actFallbackMethod.invoke(fallbackTarget, args);
    }
}
